
#include "I2C.h"


int fd,UART_fd;



/**
 * delay x ms
**/
void DEV_Delay_ms(UDOUBLE xms)
{
    usleep(xms * 1000);  // 微秒级延时（1ms = 1000μs）
    //检测应答
}

void DEV_I2C_Set_SlaveAddress(uint8_t Add)
{
    // 设置从设备地址
    if (ioctl(fd, I2C_SLAVE, Add) < 0) {
        perror("Failed to set I2C address");
        close(fd);
    }
}

void I2C_Write_Byte(uint8_t Cmd, uint8_t value)
{
//    LOGD("111111   ");
    unsigned char buf[2] = {Cmd, value};
    if ( write(fd, buf, 2) != 2) {
        LOGD("Failed to write register address");
    }
}


void I2C_Write_NByte(uint8_t *Cmd, uint8_t num)
{
    LOGD("333333   ");
//    unsigned char buf[2] = {*Cmd, num};
//   ; // 写入寄存器地址和值
//
//    if ( write(fd, buf, 2) != 1) {
//        LOGD("Failed to write register address");
//    }
}

int I2C_Read_Byte(uint8_t Cmd)
{
//    LOGD("44444   ");
    uint8_t buf[1] = {0};
    // 写入寄存器地址
    if (write(fd, &Cmd, 1) != 1) {
        LOGD("Failed to write register address");
        return -1;
    }

    // 读取从设备数据
    if (read(fd, buf, 1) != 1) {
        LOGD("Failed to write register address");
        perror("Failed to read I2C data");
        return -1;
    }
    return buf[0];
}

void I2C_Read_NByte(uint8_t Cmd, uint8_t *rbuf, uint8_t num)
{
    LOGD("66666   ");
    // 写入寄存器地址s
    if (write(fd, &Cmd, 1) != 1) {
        LOGD("Failed to write register address");
    }

    // 读取从设备数据
    if (read(fd, rbuf, num) != num) {
        LOGD("Failed to read I2C data");
    }
    LOGD("77777   ");
}

int I2C_Read_Word(uint8_t Cmd)
{
    LOGD("88888   ");
    uint8_t buf[1] = {0};
    // 写入寄存器地址
    if (write(fd, &Cmd, 1) != 1) {
        LOGD("Failed to write register address");
        return -1;
    }

    // 读取从设备数据
    if (read(fd, buf, 1) != 1) {
        LOGD("Failed to write register address");
        perror("Failed to read I2C data");
        return -1;
    }
    LOGD("99999   ");
    return buf[0];
}

void DEV_ModuleInit(char *path)
{
    if ((fd = open(path, O_RDWR)) < 0) {
        perror("Failed to open I2C bus");
    }
}


